import { mongo } from "../mogoConfig"

// 单字段索引
const run = async () => {
    const tb = mongo.db("my_test").collection("students")

    await tb.dropIndexes()

    let result = await tb.createIndex({ gpa: 1 }, { name: "gpa_idx1" })
    console.log(JSON.stringify(result))

    result = await tb.createIndex({ "location.state": 1 }, { name: "location_idx2" })
    console.log(JSON.stringify(result))

    // 对嵌入式文档创建索引
    result = await tb.createIndex({ "location": 1 }, { name: "location_idx3" })
    console.log(JSON.stringify(result))   

    let cursor = await tb.find({ gpa: 3.6 })
    console.log("查询结果1---------------------------")
    for await (const item of cursor) {
        console.log(JSON.stringify(item))
    }

    cursor = await tb.find({ gpa: { $lt: 3.4 } })
    console.log("查询结果2---------------------------")
    for await (const item of cursor) {
        console.log(JSON.stringify(item))
    }

    cursor = await tb.find({ "location.state": "California" })
    console.log("查询结果3---------------------------")
    for await (const item of cursor) {
        console.log(JSON.stringify(item))
    }

    cursor = await tb.find( { location: { city: "Sacramento", state: "California" } } )
    console.log("查询结果4---------------------------")
    for await (const item of cursor) {
        console.log(JSON.stringify(item))
    }


}


run()
    .catch((error) => {
        console.log(error)
    })
    .finally(() => {
        mongo.close()
        console.log("执行结束")
    })